package com.whc.common.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.retry.MessageRecoverer;
import org.springframework.amqp.rabbit.retry.RepublishMessageRecoverer;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;



@Configuration
@ConditionalOnClass(RabbitTemplate.class)
@Slf4j
//@ConditionalOnProperty(name = "spring.rabbitmq.listener.simple.retry.enabled",
//havingValue = "true")
public class RabbitMqConfig {

    //添加消息转化器
    @Bean
    public MessageConverter messageConverter(){
        log.info("开始自动装配rabbitmq");
        // 1.定义消息转换器
        Jackson2JsonMessageConverter jjmc = new Jackson2JsonMessageConverter();
        // 2.配置自动创建消息id，用于识别不同消息，也可以在业务中基于ID判断是否是重复消息
        jjmc.setCreateMessageIds(true);
        return jjmc;
    }
//    @Bean
//    public Queue lazyQueue(){
//        return QueueBuilder
//                .durable("lazy.queue")
//                .lazy() // 开启Lazy模式
//                .build();
//    }
    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory, @Qualifier("messageConverter") MessageConverter messageConverter) {
        // 配置 RabbitTemplate 使用 Jackson2JsonMessageConverter
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setMessageConverter(messageConverter);
        return rabbitTemplate;
    }
    //添加一个失败消息的交换机和队列
    @Bean
    public DirectExchange errorMessageExchange(){
        return new DirectExchange("error.direct");
    }

    @Bean
    public Queue errorQueue(){
        return new Queue("error.queue",true);
    }

    @Bean
    public Binding errorBinding(@Qualifier("errorQueue")Queue errorQueue, @Qualifier("errorMessageExchange") DirectExchange errorMessageExchange){
        return BindingBuilder.bind(errorQueue).to(errorMessageExchange).with("error");
    }

    @Bean
    public MessageRecoverer republishMessageRecoverer(RabbitTemplate rabbitTemplate){

        return new RepublishMessageRecoverer(rabbitTemplate,"error.direct","error");
    }


}
